var com = com || {};
com.em = com.em ||{};

com.em.User = function (){
	// for register new or update items
	this.dialogFormUser;
	// for register validator
	this.validator;
	// for show message to client
	this.alert;
	// for data table
	this.table;
	// urls
	this.url = {};
	// init plugin jgrowl
	this.initAlert();
};
com.em.User.prototype = {
	initAlert : function() {
		alert = new com.em.Alert();
	},
	
	/**
	 * Configure table and elements
	 *  
	 * @param selector
	 */
	configureTable:function(selector) { with (this) {
		table = $(selector).dataTable({
			"bProcessing"   : true,
			"bFilter"       : false,
			"bSort"         : false,
			"bInfo"         : false,
			"bLengthChange" : false,
			"bServerSide"   : true,
			"sAjaxSource"   : url.toTable,
			"sPaginationType": "full_numbers",
			"aoColumns"     : [{
				"sWidth": "10px",
				"sClass": "checkColumn",
				fnRender : function (oObj) {
					return '<input type="checkbox" name="users[]" value="'+oObj.aData[0]+'">';
				}
			},{
				   fnRender : function (oObj){
					   var id = $(oObj.aData[0]).val();
					   return '<a id="update-user-'+id+'" href="'+url.toUpdate+'/id/'+id+'">'+oObj.aData[1]+'</a>';
				   }
				},null
			],
			"fnDrawCallback" : function() {
				clickToUpdate('#tblusers a[id^=update-user-]');
			}
		});
	}},
	
	/**
	 * Show proccessing display for data table
	 * @param bShow boolean
	 */
	processingDisplay : function(bShow) {
		var settings = table.fnSettings();
		settings.oApi._fnProcessingDisplay(settings,bShow);
	},
	
	/**
	 * 
	 * @param selector
	 */
	configureDialogForm : function(selector) {with (this) {
		dialogFormUser = $( selector ).dialog({
			autoOpen: false,
			modal: true,
			width: "640",
			close: function(event, ui) {
				$(this).remove();
			}
		});
	}},
	
	/**
	 * Open dialog and manages the creation of new main group
	 * @param selector
	 */
	clickToAdd : function(selector) {with (this) {
		$(selector).bind('click',function(event) {
			event.preventDefault();
			// begin get data main group
			var action = $(this).attr('href');
			$.ajax({
				url: action,
				type: "POST",
				beforeSend : function(XMLHttpRequest){
					processingDisplay(true);
				},
				success : function(data, textStatus, XMLHttpRequest) {
					if (textStatus == 'success') {
						var contentType = XMLHttpRequest.getResponseHeader('Content-Type');
						if (contentType == 'application/json') {
							alert.show(data.message, {header : com.em.Alert.FAILURE});
						} else {
							// getting html dialog
							$('#dialog-form').html(data);
							// then config dialog
							configureDialogForm('#dialog-form-user');
							//set validator
							setValidatorForm("#form-user");
							// open dialog
							dialogFormUser.dialog('open');
							// load buttons for dialog. dialogButtons is defined by ajax
							dialogFormUser.dialog( "option" , 'buttons' , dialogButtons);
						}
					} 
				},
				complete : function(jqXHR, textStatus) {
					processingDisplay(false);
				},
				error : function(jqXHR, textStatus, errorThrown) {
					dialogFormUser.dialog('close');
					// TODO: cambiar texto a ingles
					alert.show(errorThrown,{header : com.em.Alert.ERROR});
				}
			});
		});
	}},
	
	/**
	 * Open dialog and manages the update of main group
	 * @param selector
	 */
	clickToUpdate : function(selector) {with (this) {
		$(selector).bind('click',function(event) {
			event.preventDefault();
			// begin get data main group
			var action = $(this).attr('href');
			$.ajax({
				url: action,
				type: "POST",
				beforeSend : function(XMLHttpRequest){
					processingDisplay(true);
				},
				success : function(data, textStatus, XMLHttpRequest) {
					if (textStatus == 'success') {
						var contentType = XMLHttpRequest.getResponseHeader('Content-Type');
						if (contentType == 'application/json') {
							alert.show(data.message, {header : com.em.Alert.FAILURE});
						} else {
							// getting html dialog
							$('#dialog-form').html(data);
							// then config dialog
							configureDialogForm('#dialog-form-user');
							//set validator
							setValidatorForm("#form-user");
							// open dialog
							dialogFormUser.dialog('open');
							// load buttons for dialog. dialogButtons is defined by ajax
							dialogFormUser.dialog( "option" , 'buttons' , dialogButtons);
						}
					} 
				},
				complete : function(jqXHR, textStatus) {
					processingDisplay(false);
				},
				error : function(jqXHR, textStatus, errorThrown) {
					dialogFormUser.dialog('close');
					// TODO: cambiar texto a ingles
					alert.show(errorThrown,{header : com.em.Alert.ERROR});
				}
			});
		});
	}},
	
	/**
	 * Delete n items
	 * @param selector
	 */
	clickToDelete : function(selector) {with (this) {
		$(selector).bind('click',function(event) {
			event.preventDefault();
			// serialize items checked
			var items = $('#tblusers :checked');
			var itemsChecked = items.serialize();
			if (itemsChecked == '') {
				//TODO: agregar un mensaje tipo popup indicando que no hay lista seleccionada
				return;
			}
			// input confirmation to client
			var confirmationCustomer = confirm("are you sure to delete?");			
			if( !confirmationCustomer ) {
				return;
			}
			var action = $(this).attr('href');
			// send request by ajax
			$.ajax({
				dataType : 'json', 
				type: "POST", 
				url : action,
				// get element checkbox checked
				data : itemsChecked,
				beforeSend : function(XMLHttpRequest) {
					processingDisplay(true);
				},
				success : function(data, textStatus, XMLHttpRequest) {
					if (textStatus == 'success') {
						if ( data.success ) {
							// TODO: cambiar texto a ingles
							table.fnDraw();
							alert.show(data.message);
						} else {
							alert.show(data.message, {header : com.em.Alert.FAILURE});
						}
					}
				},
				complete : function(jqXHR, textStatus) {
					processingDisplay(false);
				},
				error : function(jqXHR, textStatus, errorThrown) {
					// TODO: cambiar texto a ingles
					alert.show(errorThrown,{header : com.em.Alert.ERROR});
				}
			});
		});
	}},
	
	/**
	 * Validate  sub group form
	 * @param selector
	 */
	setValidatorForm:function(selector) {
		validator = $(selector).validate({
	        rules:{
				"name":{
					required:true,
					minlength: 3,
					maxlength: 100
				},
				"email":{
					required:true,
					minlength: 3,
					maxlength: 100
				}
	        },
	        invalidHandler: function(form, validator) {
				var errors = validator.numberOfInvalids();
				if (errors) {
					var message = errors == 1
					? 'You missed 1 field. It has been highlighted'
					: 'You missed ' + errors + ' fields. They have been highlighted';
					$("#da-validate-error").html(message).show();
				} else {
					$("#da-validate-error").hide();
				}
			}
	    });
	},
	
	/**
	 * set url for action side server
	 * @param url json
	 */
	setUrl : function(url) {
		this.url = url;
	}
};